package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.Result;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/10/8 19:13
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;


    @RequestMapping("/submitOrder")
    public Result submitOrder(@RequestBody Map map) {
        Result result = null;
        try {
            //校验验证码是否正确 ;
            //从页面获取验证码 ;
            String pagevalidateCode = map.get("validateCode").toString();
            //从页面获取电话号码 ;
            String telephone = map.get("telephone").toString();
            //从redis中获取验证码进行校验;
            String redisvalidateCode = jedisPool.getResource().get(telephone + "_001");
            //如果验证码正确;
            if (pagevalidateCode != null && pagevalidateCode.equals(redisvalidateCode)) {
                map.put("orderType", "微信预约");
                //调用service进行预约操作,预约操作就是把数据添加到数据表中;
                result = orderService.submitOrder(map);
                if (result.isFlag()) {
                    //预约成功删除redis中的键;
                    jedisPool.getResource().del(telephone + "_001");
                }
            } else {
                //如果验证码错误;
                return new Result(false, "验证码不正确,请重新输入");
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "预约失败");
        }
    }


    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Map map = orderService.findById(id);
            return new Result(true, "预约成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "获取数据失败");
        }
    }
}
